from multiprocessing import Process, Queue, Lock


def add_to_queue(queue: Queue, lock, item):
    with lock:
        queue.put(item)
        print(f"Added {item} to queue")


def process_queue():
    # 创建一个队列和一个锁
    q = Queue()
    lock = Lock()

    # 创建一些进程来向队列添加项目
    processes = []
    for i in range(5):
        p = Process(target=add_to_queue, args=(q, lock, i))
        p.start()
        processes.append(p)

    # 确保所有进程完成
    for p in processes:
        p.join()

    # 打印队列中的所有项目
    while not q.empty():
        print(q.get())


if __name__ == "__main__":
    process_queue()
